package com.gaohe.controller;

import cn.hutool.core.collection.CollectionUtil;
import com.gaohe.common.R;
import com.gaohe.pojo.Classes;
import com.gaohe.pojo.User;
import com.gaohe.pojo.UserCard;
import com.gaohe.pojo.UserClass;
import com.gaohe.service.ClassesService;
import com.gaohe.service.UserCardService;
import com.gaohe.service.UserClassService;
import com.gaohe.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;

@RequestMapping("userClasses")
@RestController
@Slf4j
public class UserClassController {
    @Autowired
    ClassesService classesService;
//    查询用户课程
    @GetMapping("/{userId}")
    public R getClassByUserId(@PathVariable Long userId) {
        List<Classes> list = classesService.getClassByUserId(userId);
        return R.success(list);
    }

    @Autowired
    UserCardService userCardService;

    @Autowired
    UserService userService;

    @Autowired
    UserClassService userClassService;

    @GetMapping("/chooseClasses")
    private R chooseClasses(@RequestBody Map<String, Long> map) {
        log.info("会员选课业务");
//        1.接受用户id和课程id
        Long userId = map.get("userId");
        Long classId = map.get("classId");
//        2.查询课程信息
        Classes byId = classesService.getById(classId);
//        3.课程过期
        if (!byId.getEnd_time().isAfter(LocalDateTime.now())) {
            log.info("该课程已过期");
            return R.error("课程已过期");
        }
//        4.课程已满
        if (byId.getPnum() >= byId.getPmax()) {
            log.info("课程已满");
            return R.error("课程已满");
        }
//        5.查询用户卡的信息
        List<UserCard> cards = userCardService.getCardByUserId(userId);

//        6.过期，次数卡用尽，禁用，卡和课tags标签有关联
        cards = cards.stream().filter(item -> {
            return item.getEndDate().isAfter(LocalDate.now());
        }).filter(item -> {
            boolean flag = false;
            if (item.getType() == "期限卡") {
                flag = true;
            }
            if (item.getType() == "次数卡") {
                flag = true;
            }
            return flag;
        }).filter(item -> {
            // 把过期的卡篇过滤掉
            return item.getEndDate().isAfter(LocalDate.now());
        }).filter(item -> {// 卡片标签比对
            String[] tags_card = item.getTags().split(",");
            String[] tags_classes = byId.getTags().split(",");
            // 连个集合取交集 卡片可用的筛选出来
            Collection<String> intersection = CollectionUtil
                    .intersection(Arrays.asList(tags_card), Arrays.asList(tags_classes));
            return intersection.size() > 0;

        }).filter(item -> {// 把没有次数的卡过滤掉
            boolean flag = false;
            if (item.getType().equals("期限卡")) {
                item.setDisabled(true);
                flag = true;
            } else if (item.getType().equals("次卡")
                    && item.getCount() >= 1) {
                item.setDisabled(true);
                flag = true;
            }
            return flag;
        }).map(item -> {
            // 最后把所有可用的卡片收集出来
            item.setDisabled(true);
            return item;
        }).toList();
        // 7.若果集合为null 或者集合为空 则无权限卡
        if(cards == null || CollectionUtil.isEmpty(cards)){
            return R.error("无权限卡");
        }
        //        8.遍历所有可用卡片
        UserCard thisUserCard = null;
        // 8.1若果这个卡位期限卡，立即使用
        for (UserCard userCard : cards) {
            if(userCard.getType().equals("期限卡")){
                thisUserCard = userCard;
                break;
            }
        }
        // 8.2若果没有期限卡 使用次卡
        if(thisUserCard==null){
            for (UserCard userCard : cards) {
                if (userCard.getType().equals("次卡")){
                    thisUserCard = userCard;
                    thisUserCard.setCount(userCard.getCount()-1);
                    userCardService.updateById(thisUserCard);
                    break;
                }
            }
        }

        // 9.把会员添加到课程中
        User user = userService.getById(userId);//获取用户信息
        UserClass userClass1 = new UserClass();
        userClass1.setUserId(userId);
        userClass1.setClassId(classId);
        userClass1.setClassName(byId.getName());
        userClass1.setUserName(user.getName());
        userClass1.setCreateTime(LocalDateTime.now());
        userClass1.setStatus(0);
        userClass1.setIsDeleted(0);
        userClass1.setTags(byId.getTags());
        boolean save = userClassService.save(userClass1);
        return R.success("选课成功");

    }
}
